angular.module('Circumference')
    .controller('Circumference.CircumferenceCtrl', ['$scope', '$state', '$http', '$ionicLoading', '$stateParams', '$ionicPopup', '$ionicModal', 'Http', 'imanDialog', 'DevicePort', 'Device', 'Circumference.Param', 'Help', 'User',
        function ($scope, $state, $http, $ionicLoading, $ionicPopup, $ionicModal, $stateParams, Http, imanDialog, DevicePort, Device, Param, Help, User) {
            $scope.data = {
                Barcode: '',
                photo: User.get('Image')
            };

            var toast;

            $scope.imgPath = {
                cycle: u9ImHd.getFullPath('/img/cycle.png', 'Circumference')
            };

            $scope.showToast = function (styleMes) {
                if (toast) {
                    toast.hide();
                }
                toast = imanDialog.toast({
                    message: styleMes,
                    position: 'center',
                    duration: false,
                    backdropClickToClose: false,
                    hardwareBackButtonClose: false
                });
            };

            $scope.showToast('请扫描单品信息');

            $scope.hideToast = function () {
                if (toast) {
                    toast.hide();
                    toast = null;
                }
            };

            $scope.$on('$ionicView.afterEnter', function () {
                DevicePort.open({
                    device: 0,
                    baudrate: 115200,
                    parseFn: true
                }).then(function () {
                    imanDialog.toastBottom("成功");
                }, function (err) {
                    imanDialog.toastBottom(err);
                });
                // getQcInfo('6482533');
                //初始化重量和周径数据
                $scope.param = Param.getParam();
            });

            $scope.$on('devicePort.DataReceived', function (e, barcode) {
                $scope.data.Barcode = barcode;
                getQcInfo(barcode);
            });

            $scope.$on('$ionicView.beforeLeave', function () {
                DevicePort.close();
                if (toast) {
                    toast.hide();
                    toast = null;
                }
            });

            $scope.openMagnifier = function (value) {
                if (value.length > 0) {
                    $state.go('Magnifiers');
                } else {
                    $scope.showToast('请扫描单品信息');
                }
            };

            /**
             * [goCircumference 跳转到周径测量页面]
             *
             */
            $scope.goPound = function () {
                Help.loadApp('Pound').then(function () {
                    DevicePort.close();
                    if (toast) {
                        toast.hide();
                        toast = null;
                    }
                    $state.go('Pound', {
                        Barcode: $scope.data.Barcode
                    });
                }, function () {
                    imanDialog.toastBottom('进入磅重应用失败，请确认是否已正确安装然后重试。');
                });
            };

            $scope.init = function () {
                Param.clearParam();
                getQcInfo($stateParams.Barcode);
            };

            $scope.init();

            function getQcInfo(Barcode) {
                if (!Barcode) {
                    return;
                }
                $ionicLoading.show();
                Param.setBarcodeString(Barcode);
                Http.post({
                    url: '/api/Wrapper/getWrapperInfo',
                    data: {
                        Parameter: {
                            Barcode: Barcode,
                            TerminalUniqueID: Device.getUUID(),
                            HDWork: Device.get().Work
                        }
                    }
                }).then(function (info) {
                    if (info.basicInfo.MOCode) {
                        $scope.hideToast();
                    }
                    var qcStandardArr = info.qcStandard;

                    qcStandardArr.sort(arraySortByKey("QCCode"));

                    var magnifierCycle = [];
                    angular.forEach(qcStandardArr, function (obj) {
                        if (obj.QCCode.indexOf('ZJ') > -1) {
                            magnifierCycle.push(obj);
                        }
                    });

                    /**
                     * 处理周径信息  分组
                     * @param arr 数据
                     * @param size 组数
                     * @returns {Array}
                     */
                    var chunk = function (arr, size) {
                        var newArr = [];
                        for (var i = 0; i < arr.length; i += size) {
                            newArr.push(arr.slice(i, i + size));
                        }
                        return newArr;
                    };

                    $scope.param = Param.setParam({
                        key: 'cycle',
                        value: chunk(magnifierCycle, 3)
                    });

                    $scope.param = Param.setParam({
                        key: 'magnifierCycle',
                        value: magnifierCycle
                    });

                    $scope.data.barcode = info.basicInfo;
                    Param.setBarcode(info.basicInfo);
                    $scope.data.Users = info.basicInfo.Users;
                    Param.setUsers(info.basicInfo.Users);
                    $scope.param = Param.getParam();
                })['finally'](function () {
                    $ionicLoading.hide();
                });
            }

            //数组排序
            function arraySortByKey(key) {
                return function (objFirst, objSecond) {
                    var aStr, bStr;
                    if (typeof objFirst === "object" && typeof objSecond === "object" && objFirst && objSecond) {
                        aStr = objFirst[key];
                        bStr = objSecond[key];
                        if (aStr === bStr) {
                            return 0;
                        }
                        if (typeof aStr === typeof bStr) {
                            return aStr < bStr ? -1 : 1;
                        }
                        return typeof aStr < typeof bStr ? -1 : 1;
                    } else {
                        throw ("error");
                    }
                };
            }
        }
    ]);
